//用户仓库
import { defineStore } from 'pinia'
import {setToken, getToken, removeToken } from '@/utils/auth/index'
import {logout} from '@/api/login'

import { ref } from 'vue'
//引入所有路由
import { constanceRoute} from '@/router/routes'
//引入深拷贝方法,因为过滤过程中会把异步路由修改
//@ts-expect-error
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router'

//用于过滤当前用户需要展示的异步路由
function filterRoute(constanceRoute, routes) {
  return constanceRoute.filter((item) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        //硅谷333账号:product\trademark\attr\sku
        item.children = filterRoute(item.children, routes)
      }
      return true
    }
  })
}


export const useUserStore = defineStore(
  'UID',
  () => {
    let satoken=ref('')
    const menuRoutes=ref()//同sys路由
    const uid=ref('')
    const username=ref('')
    const avatar=ref('')
    const userRole=ref([])
    const userVO=ref({
      userName:'',
      userGender:'',
      userDep:''//部门班级
    })
    const lastLoginTime=ref('')
    let useroutename=ref([])//自定义为了更好路由拦截
    const userInfo = async (data) => {
         uid.value = data.uid
         satoken.value = data.satoken
         username.value = data.username
         avatar.value = data.avatar
         userVO.value = data.userVO
         userRole.value = data.userRole
         lastLoginTime.value = data.lastLoginTime
         const rs=data.systemMenus;
         rs.push('layout')
         rs.push('layout2')
        //  console.log("routes ", data.systemMenus)
        useroutename.value = rs
         //和后端匹配
        const userRoute=filterRoute(
          cloneDeep(constanceRoute),//深度拷贝
          rs
        )

        // console.log("USERoutes: ", userRoute)
        menuRoutes.value = [...userRoute];
        //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        [...userRoute].forEach((route) => {
          router.addRoute(route)
        })
        // console.log("menuRoutes: ", menuRoutes.value)
        // console.log("router: ", router)
    }
    let userLogout = async()=> {
      //清除用户数据
        await logout();
        uid.value = ""
        satoken.value = ""
        username.value = ""
        avatar.value = ""
        userVO.value = {}
        userRole.value = []
        menuRoutes.value=[]  
        // 移除名为 "UID" 的 localStorage 键值对
        localStorage.removeItem('UID');
        window.localStorage.clear()
    };

    return {
      satoken,
      uid,
      username,
      avatar,
      userRole,
      userVO,
      menuRoutes,
      useroutename,
      lastLoginTime,
      userInfo,
      userLogout,
    }
  },
  {
       persist:true,
  }
)
